<template>
  <div class="class-list-container">
    <el-card class="class-list-card">
      <template #header>
        <div class="card-header">
          <h2>班级列表</h2>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索班级名称"
              clearable
              class="search-input"
              @clear="handleSearchClear"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="navigateToAdd">
              <el-icon><Plus /></el-icon> 添加班级
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredClasses"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="name" label="班级名称" min-width="120" />
        <el-table-column prop="courseName" label="所属课程" min-width="120" />
        <el-table-column prop="studentCount" label="学生人数" width="100" align="center" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleViewStudents(scope.row)"
            >
              查看学生
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="filteredClasses.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredClasses.length"
        />
      </div>
    </el-card>

    <!-- 学生列表对话框 -->
    <el-dialog
      v-model="studentsDialogVisible"
      title="班级学生列表"
      width="70%"
    >
      <el-table
        :data="classStudents"
        style="width: 100%"
        border
        v-loading="studentsLoading"
      >
        <el-table-column prop="studentId" label="学号" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="grade" label="年级" width="100" />
        <el-table-column prop="major" label="专业" min-width="150" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              @click="handleRemoveStudent(scope.row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer">
        <el-button @click="studentsDialogVisible = false">关闭</el-button>
        <el-button type="success" @click="handleAddStudent">
          <el-icon><plus /></el-icon> 添加学生
        </el-button>
        <el-button type="primary" @click="handleImportStudents">
          <el-icon><upload /></el-icon> 导入学生
        </el-button>
      </div>
    </el-dialog>

    <!-- 导入学生对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入学生名单"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        accept=".xlsx,.xls,.csv"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件(.xlsx, .xls)或CSV文件，包含学号、姓名、年级、专业等信息
          </div>
        </template>
      </el-upload>
      <div class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="importStudents" :loading="importing">导入</el-button>
      </div>
    </el-dialog>

    <!-- 添加学生对话框 -->
    <el-dialog
      v-model="addStudentDialogVisible"
      title="添加学生"
      width="500px"
    >
      <el-form
        :model="studentForm"
        :rules="studentRules"
        ref="studentFormRef"
        label-width="80px"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="studentForm.grade" placeholder="请选择年级" style="width: 100%">
            <el-option
              v-for="year in gradeOptions"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="studentForm.major" placeholder="请输入专业" />
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="addStudentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddStudent" :loading="addingStudent">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive, nextTick } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, UploadFilled } from '@element-plus/icons-vue'
import FileParserFactory from '@/utils/FileParserFactory'
import logger from '@/utils/Logger'
import { classApi, studentApi } from '@/utils/api'

export default {
  name: 'ClassList',
  components: {
    Search,
    Plus,
    UploadFilled
  },
  setup() {
    const store = useStore()
    const router = useRouter()

    // 状态
    const loading = ref(false)
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const studentsDialogVisible = ref(false)
    const studentsLoading = ref(false)
    const classStudents = ref([])
    const currentClass = ref(null)
    const importDialogVisible = ref(false)
    const addStudentDialogVisible = ref(false)
    const uploadFile = ref(null)
    const importing = ref(false)
    const addingStudent = ref(false)
    const studentFormRef = ref(null)

    // 学生表单
    const studentForm = reactive({
      studentId: '',
      name: '',
      grade: '',
      major: ''
    })

    // 学生表单验证规则
    const studentRules = {
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { pattern: /^\d{5,12}$/, message: '学号必须为5-12位数字', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
      ],
      grade: [
        { required: true, message: '请选择年级', trigger: 'change' }
      ],
      major: [
        { required: true, message: '请输入专业', trigger: 'blur' }
      ]
    }

    // 年级选项（当前年份-10年 到 当前年份+1年）
    const currentYear = new Date().getFullYear()
    const gradeOptions = Array.from({ length: 12 }, (_, i) => (currentYear - 10 + i).toString())

    // 计算属性
    const filteredClasses = computed(() => {
      const classes = store.getters.getClasses
      if (!searchQuery.value) {
        return classes
      }

      return classes.filter(c =>
        c.name.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    })

    // 方法
    const loadClasses = async () => {
      loading.value = true
      try {
        // 从后端API获取班级数据
        const response = await classApi.getAllClasses()

        // 处理响应数据
        let classes = []
        if (response && Array.isArray(response)) {
          classes = response.map(classItem => ({
            id: classItem.id.toString(),
            name: classItem.name,
            courseId: classItem.courseId.toString(),
            courseName: classItem.courseName || '未知课程', // 后端可能需要返回课程名称
            studentCount: classItem.studentCount || 0
          }))
        } else {
          console.warn('后端返回的班级数据格式不符合预期', response)
        }

        store.dispatch('setClasses', classes)
        logger.info('班级列表加载成功', { count: classes.length })
      } catch (error) {
        logger.error('加载班级列表失败', error)
        ElMessage.error('加载班级列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearchClear = () => {
      searchQuery.value = ''
    }

    const navigateToAdd = () => {
      router.push('/class/add')
    }

    const handleEdit = (row) => {
      router.push(`/class/edit/${row.id}`)
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除班级 "${row.name}" 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await store.dispatch('deleteClass', row.id)
          ElMessage.success('班级删除成功')
          logger.info('班级删除成功', { classId: row.id, className: row.name })
          // 重新加载班级列表
          loadClasses()
        } catch (error) {
          logger.error('删除班级失败', error)
          ElMessage.error('删除班级失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    const handleViewStudents = async (row) => {
      currentClass.value = row
      studentsLoading.value = true
      studentsDialogVisible.value = true

      try {
        // 从后端API获取学生数据
        const response = await studentApi.getStudentsByClass(row.id)

        // 处理响应数据
        let students = []
        if (response && Array.isArray(response)) {
          students = response.map(student => ({
            id: student.id.toString(),
            studentId: student.studentId,
            name: student.name,
            grade: student.grade,
            major: student.major,
            classId: student.classId.toString()
          }))
        } else {
          console.warn('后端返回的学生数据格式不符合预期', response)
        }

        classStudents.value = students
        logger.info('班级学生列表加载成功', { classId: row.id, count: students.length })
      } catch (error) {
        logger.error('加载班级学生列表失败', error)
        ElMessage.error('加载班级学生列表失败')
      } finally {
        studentsLoading.value = false
      }
    }

    const handleRemoveStudent = (student) => {
      ElMessageBox.confirm(
        `确定要将学生 "${student.name}" 从班级中移除吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          // 调用API删除学生
          await store.dispatch('deleteStudent', student.id)

          // 从班级中移除学生
          classStudents.value = classStudents.value.filter(s => s.id !== student.id)

          // 更新班级学生数量
          const updatedClass = {
            ...currentClass.value,
            studentCount: classStudents.value.length
          }
          await store.dispatch('updateClass', { id: updatedClass.id, classData: updatedClass })

          ElMessage.success('学生已从班级中移除')
          logger.info('学生从班级中移除', { studentId: student.id, studentName: student.name, classId: currentClass.value.id })
        } catch (error) {
          logger.error('移除学生失败', error)
          ElMessage.error('移除学生失败')
        }
      }).catch(() => {
        // 取消移除
      })
    }

    const handleImportStudents = () => {
      importDialogVisible.value = true
    }

    const handleAddStudent = () => {
      // 重置表单
      studentForm.studentId = ''
      studentForm.name = ''
      studentForm.grade = currentYear.toString()
      studentForm.major = ''

      // 显示对话框
      addStudentDialogVisible.value = true

      // 下一个 tick 后重置表单验证
      nextTick(() => {
        if (studentFormRef.value) {
          studentFormRef.value.resetFields()
        }
      })
    }

    const submitAddStudent = async () => {
      if (!studentFormRef.value) return

      await studentFormRef.value.validate(async (valid) => {
        if (valid) {
          addingStudent.value = true

          try {
            // 检查学号是否已存在
            const studentExists = classStudents.value.some(
              student => student.studentId === studentForm.studentId
            )

            if (studentExists) {
              ElMessage.error('该学号已存在于班级中')
              return
            }

            // 创建新学生对象
            const newStudent = {
              studentId: studentForm.studentId,
              name: studentForm.name,
              grade: studentForm.grade,
              major: studentForm.major,
              classId: currentClass.value.id
            }

            // 调用API创建学生
            const createdStudent = await store.dispatch('createStudent', newStudent)

            // 添加到班级学生列表
            classStudents.value.push(createdStudent)

            // 更新班级学生数量
            const updatedClass = {
              ...currentClass.value,
              studentCount: classStudents.value.length
            }
            await store.dispatch('updateClass', { id: updatedClass.id, classData: updatedClass })

            ElMessage.success('学生添加成功')
            logger.info('学生添加成功', {
              studentId: newStudent.studentId,
              studentName: newStudent.name,
              classId: currentClass.value.id
            })

            // 关闭对话框
            addStudentDialogVisible.value = false
          } catch (error) {
            logger.error('添加学生失败', error)
            ElMessage.error('添加学生失败')
          } finally {
            addingStudent.value = false
          }
        }
      })
    }

    const handleFileChange = (file) => {
      uploadFile.value = file.raw
    }

    const importStudents = async () => {
      if (!uploadFile.value) {
        ElMessage.warning('请先选择文件')
        return
      }

      importing.value = true
      try {
        // 使用工厂模式创建文件解析器
        const parser = FileParserFactory.createParserFromFile(uploadFile.value)
        const studentsData = await parser.parse(uploadFile.value)

        // 处理学生数据
        const students = studentsData.map(data => ({
          studentId: data['学号'] || '',
          name: data['姓名'] || '',
          grade: data['年级'] || '',
          major: data['专业'] || '',
          classId: currentClass.value.id
        }))

        // 调用API导入学生
        const importedStudents = await store.dispatch('importStudents', {
          classId: currentClass.value.id,
          file: uploadFile.value
        })

        // 添加到当前班级学生列表
        if (importedStudents && Array.isArray(importedStudents)) {
          classStudents.value = [...classStudents.value, ...importedStudents]
        }

        // 更新班级学生数量
        const updatedClass = {
          ...currentClass.value,
          studentCount: classStudents.value.length
        }
        await store.dispatch('updateClass', { id: updatedClass.id, classData: updatedClass })

        ElMessage.success(`成功导入 ${students.length} 名学生`)
        logger.info('学生导入成功', { count: students.length, classId: currentClass.value.id })
        importDialogVisible.value = false
      } catch (error) {
        logger.error('导入学生失败', error)
        ElMessage.error(`导入学生失败: ${error.message}`)
      } finally {
        importing.value = false
      }
    }

    // 生命周期钩子
    onMounted(() => {
      loadClasses()
    })

    return {
      loading,
      searchQuery,
      currentPage,
      pageSize,
      filteredClasses,
      studentsDialogVisible,
      studentsLoading,
      classStudents,
      currentClass,
      importDialogVisible,
      addStudentDialogVisible,
      importing,
      addingStudent,
      studentForm,
      studentFormRef,
      studentRules,
      gradeOptions,
      handleSearchClear,
      navigateToAdd,
      handleEdit,
      handleDelete,
      handleViewStudents,
      handleRemoveStudent,
      handleImportStudents,
      handleAddStudent,
      submitAddStudent,
      handleFileChange,
      importStudents
    }
  }
}
</script>

<style scoped>
.class-list-container {
  max-width: 1200px;
  margin: 0 auto;
}

.class-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.search-input {
  width: 250px;
  margin-right: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
